#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#
# Alexander street uses a seperate password for each college and datasource. They also use MD5 to encrypt the password before
# sending it to them.
#
# always returns all months and all colleges unless collegeID is passed as argument
#

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Date::Calc qw(Decode_Month Add_Delta_YM);

use avsCommon;


my ($content, $response, $request, $url);

dbsetup();

my $begperiod = myperiod($begyear, $begmonth);
my $endperiod = myperiod($endyear, $endmonth);

# go through all logins for Alexander Street
do {
  getStats ();
} while ($sthlogin->fetch);

dbshutdown();

# uses vendorId, collegeid, user, pass. retrieves stats and updates db
sub getStats {
	my $ua = new LWP::UserAgent(keep_alive=>1);
	$ua->cookie_jar( {} );
	
	# get challenge string 
	$url = 'http://partners.classical.com/index.php';
	$response = $ua->request(GET $url);
	if (!$response->is_success) {
		die "#error:$0: GET challenge $url" . $response->status_line;
	};

	$content=$response->decoded_content;
	
	#extract challenge from response
	$content =~ /PSESS\=(?<psess>.*?)\".*?\"challenge\" value\=\"(?<challenge>.*?)\"/s;

	my	$challenge = $+{challenge};
	my	$psess = $+{psess};

	# encrypt password
	my	$md5 = Digest::MD5->new;
			$md5->add($password);
	my	$digest = $md5->hexdigest;

	#now encrypt challenge, username and encrypted password
	$md5 = Digest::MD5->new;
	$md5->add("$username:$digest:$challenge");
	$digest = $md5->hexdigest;

	# now ready to login and get data at same time
	$url = "http://partners.classical.com/tab_service_reports/monthly_totals.php?product=s:all&PSESS=$psess";

	$response = $ua->request(POST $url,
		[	'username' 	=>$username,
			'password' 	=>'',
			'challenge'	=>$challenge,
			'response'	=>$digest ] ) ;

	if (!$response->is_success) {
		die "#error:$0: POST login $url" . $response->status_line;
	};

	# here is the statistical data
	$content=$response->decoded_content;

	# save contents for possible debugging
	savecontent('AlexanderStreet', $username, $content);

	while ($content =~ /Monthly totals for .*?(-\s|\()(?<datasource>.*?)<\/h1>(?<data>.*?)<\/table>/gc) {

		my $datasource = $+{datasource};
		# alexanderstreet returns empty datasources when people quit paying
		if ($datasource eq 'unlimited SU)' || $datasource eq ' (unlimited SU)') {
			$datasource = $option1 . '(unlimited SU)';
		};
		my $data = $+{data};

		#get monthly data from table
		while ($data =~ /(?<month>\w*?), (?<year>\d{4}).*?\<td.*?\>(?<sessions>\d+)(\<\/td\>.*?){4}\<td.*?\>(?<searches>\d+)/sg) {
			my	$period = myperiod($+{year},$+{month});
			if ($begperiod le $period && $period le $endperiod) {
				my $sessions = $+{sessions};
				my $searches = $+{searches};
				print "$vendorid $collegeid $period $datasource $sessions $searches\n";
				$sthstats->execute($vendorid, $collegeid, $datasource, $period, $sessions, 1)
					or die "#error: sthstats 1 execute failed, check end of log";
				$sthstats->execute($vendorid, $collegeid, $datasource, $period, $searches, 2)
					or die "#error: sthstats 2 execute failed, check end of log";
			}
		}
	}

	# logout the session
	$url = 'http://partners.classical.com/logout.php';
	$response = $ua->request(GET $url);
};

